const fs = require('fs')
const root = process.cwd()

function addMapping(router, mapping) {
    for (let url in mapping) {
        if (url.indexOf('GET ')===0) {
            const path = url.substring(4)
            router.get(path, mapping[url])
        } else if (url.indexOf('POST ') === 0) {
            const path = url.substring(5)
            router.post(path, mapping[url])
        } else if (url.indexOf('PUT ') === 0) {
            const path = url.substring(4)
            router.put(path, mapping[url])
        } else if (url.indexOf('DELETE ') === 0) {
            const path = url.substring(7)
            router.del(path, mapping[url])
        }
    }
}

function addControllers(router, dir) {
    const mapping = require(root + dir)
    addMapping(router, mapping)
}

module.exports = function (dir) {
    let controller_dir = dir || '/routes/api',
        router = require('koa-router')()
    addControllers(router, controller_dir)
    return router
}